<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 添加按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddDialog">添加分类</el-button>
        </el-col>
      </el-row>

      <!-- 分类表格 -->
      <el-table :data="catelist" border row-key="cat_id">
        <!-- 自定义索引列 -->
        <el-table-column label="#" type="index">
          <template v-slot="scope">
            <!-- 判断当前行的数据是否为一级分类，如果不是，则不展示索引 -->
            <span>{{scope.row.cat_level === 0 ? scope.row.index: ''}}</span>
          </template>
        </el-table-column>
        <el-table-column label="分类名称" prop="cat_name"></el-table-column>
        <el-table-column label="是否有效">
          <template v-slot="scope">
            <i class="el-icon-error" v-if="scope.row.cat_deleted"></i>
            <i class="el-icon-success" v-else></i>
          </template>
        </el-table-column>
        <el-table-column label="排序" prop="cat_level">
          <template v-slot="scope">
            <el-tag effect="dark" size="mini" v-if="scope.row.cat_level === 0">一级</el-tag>
            <el-tag effect="dark" size="mini" type="success" v-else-if="scope.row.cat_level === 1">二级</el-tag>
            <el-tag effect="dark" size="mini" type="warning" v-else>三级</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDialog(scope.row.cat_id)">编辑</el-button>
            <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeCate(scope.row.cat_id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryObj.pagenum" :page-sizes="[5, 10, 15, 20]" :page-size="queryObj.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>

    <!-- 添加分类的对话框 -->
    <el-dialog title="添加商品分类" :visible.sync="addDialogVisible" width="50%" @close="onAddDialogClose">
      <!-- 添加分类的表单 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="80px">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <el-cascader v-model="cascaderValue" :options="parentCateList" :props="cascaderProps" clearable @change="onCascaderChange"></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addNewCate">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改分类的对话框 -->
    <el-dialog title="修改分类" :visible.sync="editDialogVisible" width="50%" @close="onEditDialogClose">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="80px">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      catelist: [],
      queryObj: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      total: 0,
      addDialogVisible: false,
      addForm: {
        // 父分类Id
        cat_pid: 0,
        // 分类名称
        cat_name: '',
        // 分类等级
        cat_level: 0
      },
      addFormRules: {
        cat_name: [
          { required: true, message: '分类名称不能为空', trigger: 'blur' },
          { min: 1, max: 8, message: '分类名称长度在1~8个字符', trigger: 'blur' }
        ]
      },
      // 父级分类列表
      parentCateList: [],
      // 级联选择框的配置项
      cascaderProps: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
        checkStrictly: true
      },
      cascaderValue: [],
      editDialogVisible: false,
      editForm: {},
      editFormRules: {
        cat_name: [
          { required: true, message: '分类名称不能为空', trigger: 'blur' },
          { min: 1, max: 8, message: '分类名称长度在1~8个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 获取所有分类列表数据
    async getCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: this.queryObj
      })
      if (res.meta.status !== 200) return this.$message.error('获取分类数据失败！')

      res.data.result.forEach((item, i) => (item.index = i + 1))

      this.catelist = res.data.result
      this.total = res.data.total
    },
    handleSizeChange(newSize) {
      this.queryObj.pagesize = newSize
      this.getCateList()
    },
    handleCurrentChange(newCurrent) {
      this.queryObj.pagenum = newCurrent
      this.getCateList()
    },
    showAddDialog() {
      this.getParentCateList()
      this.addDialogVisible = true
    },
    async getParentCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: {
          type: 2
        }
      })

      if (res.meta.status !== 200) return this.$message.error('获取分类列表数据失败！')

      this.parentCateList = res.data
    },
    onCascaderChange(arr) {
      if (arr.length === 0) {
        this.addForm.cat_pid = 0
      } else {
        this.addForm.cat_pid = arr[arr.length - 1]
      }
      this.addForm.cat_level = arr.length
    },
    onAddDialogClose() {
      // 重置表单数据
      this.addForm = {
        // 父分类Id
        cat_pid: 0,
        // 分类名称
        cat_name: '',
        // 分类等级
        cat_level: 0
      }
      // 清空验证状态
      this.$refs.addFormRef.resetFields()
      // 清空级联选择框的值
      this.cascaderValue = []
    },
    addNewCate() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return

        const { data: res } = await this.$http.post('categories', this.addForm)

        if (res.meta.status !== 201) return this.$message.error('添加商品分类失败！')

        this.$message.success('添加商品分类成功！')
        this.getCateList()
        this.addDialogVisible = false
      })
    },
    // 移除分类
    async removeCate(id) {
      const confirmResult = await this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (confirmResult !== 'confirm') return

      const { data: res } = await this.$http.delete('categories/' + id)
      if (res.meta.status !== 200) return this.$message.error('删除分类失败！')

      this.$message.success('删除分类成功！')

      if (this.catelist.length === 1 && this.queryObj.pagenum > 1) {
        this.queryObj.pagenum--
      }

      this.getCateList()
    },
    // 展示修改分类的对话框
    async showEditDialog(id) {
      const { data: res } = await this.$http.get(`categories/${id}`)
      if (res.meta.status !== 200) return this.$message.error('获取分类信息失败！')
      this.editForm = res.data
      this.editDialogVisible = true
    },
    onEditDialogClose() {
      this.editForm = {}
      this.$refs.editFormRef.resetFields()
    },
    editCate() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return

        const { data: res } = await this.$http.put(`categories/${this.editForm.cat_id}`, {
          cat_name: this.editForm.cat_name
        })

        if (res.meta.status !== 200) return this.$message.error('更新商品分类失败！')

        this.$message.success('更新商品分类成功！')
        this.getCateList()
        this.editDialogVisible = false
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-icon-success {
  color: #39ce39;
}

.el-icon-error {
  color: #ff3b3b;
}

.el-cascader {
  width: 100%;
}
</style>